﻿Imports Microsoft.Office.Interop
Imports System.Text.RegularExpressions
Imports System.IO

Public Class Form1

    Dim dao As CacheOperation


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        
        CType(Me.Settings.DropDown, ToolStripDropDownMenu).ShowCheckMargin = False
        CType(Me.Settings.DropDown, ToolStripDropDownMenu).ShowImageMargin = False
        dao = New CacheOperation
        Me.DataGridView1.Focus()
    End Sub

    Private Sub CommitClick(sender As Object, e As EventArgs) Handles Commit.Click
        If (Me.CurrentItems.Count = 0 And Me.CachedTypes.Count = 0) Then
            MsgBox("Нет прайсов для сборки.")
            Exit Sub
        End If

        ''nds check
        'Try
        '    NDS_COEFF = HardConvertToDouble(Me.NDSCoeff.Text)
        'Catch ex As ArgumentException
        '    MsgBox("Коэффициент для расчета НДС не распознан программой")
        '    Exit Sub
        'End Try

        For Each go As GridObject In Me.CurrentItems
            If go.path = "" Then
                MsgBox("Не задано имя файла для прайса: " + go.type + ".")
                Exit Sub
            End If
        Next

        If (Me.Currency.Text = "") Then ' no course set
            MsgBox("Не задан курс доллара к рублю.")
            Exit Sub
        Else
            BYR_USD_CONV = Convert.ToInt32(Me.Currency.Text)
        End If

       
        Dim succ As String = Nothing
        Dim err As String = Nothing

        'matches
        If (SaveTXTDialog.ShowDialog() = Windows.Forms.DialogResult.Cancel) Then
            MsgBox("Действие отменено.")
            Exit Sub
        End If
        succ = SaveTXTDialog.FileName

        'If (SaveCSVDialog.ShowDialog() = Windows.Forms.DialogResult.Cancel) Then
        '    MsgBox("Действие отменено.")
        '    Exit Sub
        'End If
        'err = SaveCSVDialog.FileName

        Try
            If (File.Exists(succ)) Then
                File.Delete(succ)
            End If
            'If (File.Exists(err)) Then
            '    File.Delete(err)
            'End If
        Catch x As IOException
            MsgBox("Ошибка при задании пути к текстовым файлам. Проверьте, открыт ли файл (файлы) в других программах, и закройте их либо укажите другой путь для файлов.")
            Exit Sub
        End Try



        Me.Enabled = False
        My.Forms.Dictionary.Close()
        Me.Cursor = Cursors.WaitCursor

        Try
            dao.cache(succ, err)
            dao.commit()
            If MsgBox("Отправить запрос на сайт?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                dao.send()
            End If
            MsgBox("Сборка успешно завершена.")
        Catch x As Exception
            MsgBox("Неизвестная ошибка. Попробуйте перезапустить приложение и исключить возможные ошибки при вводе исходных данных.")
            With File.CreateText(Directory.GetCurrentDirectory() + "\" + errorlogfile)
                .WriteLine()
                .WriteLine(Date.UtcNow.ToString)
                .WriteLine("type:" + x.GetType.ToString)
                .WriteLine("msg:" + x.Message)
                .WriteLine("obj:" + x.Source)
                .WriteLine("trace:" + x.StackTrace)
                .WriteLine("---")
                .Flush()
                .Close()
            End With
            Exit Sub
        Finally
            Me.Enabled = True
            Me.Cursor = Cursors.Default

        End Try


    End Sub

    Private Sub GetFileClick(sender As Object, e As EventArgs)
        'InputFile.Reset()
        Dim number As Integer
        number = Convert.ToInt32(Regex.Match(sender.name, "[0-9]*$").ToString)
        'MsgBox(number)
        InputFile.ShowDialog()
        'MsgBox(InputFile.FileName + sender.Name)
    End Sub

    Private Sub AddFile(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
        If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
            If (e.ColumnIndex <> 0) Then ' if clicked on match file column or source file column
                If DataGridView1.Item(0, e.RowIndex).Value = "" Then
                    MsgBox("Сперва укажите тип.")
                    Exit Sub
                End If
                If (InputFile.ShowDialog() = Windows.Forms.DialogResult.OK) Then
                    DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = InputFile.FileName
                End If
            End If
        End If
    End Sub

    Private Sub Currency_TextChanged(sender As Object, e As EventArgs) Handles Currency.TextChanged
        Dim s As TextBox = DirectCast(sender, TextBox)
        If (Regex.IsMatch(s.Text, "\D")) Then
            'MsgBox("Строка с курсом содержит нецифровые символы, они были удалены")
            s.Text = Regex.Replace(s.Text, "\D", "")
        End If
    End Sub
    Private Sub Dict_Click(sender As Object, e As EventArgs) Handles Dict.Click
        My.Forms.Dictionary.Show()
    End Sub

    Private Sub MenuClearCache_Click(sender As Object, e As EventArgs) Handles ClearCache.Click
        dao.clearcache()
    End Sub

    Private Sub Coeff_Click(sender As Object, e As EventArgs) Handles Coeff.Click
        My.Forms.Coefficients.Show()
    End Sub
End Class